package com.pan.api.format;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 有点难受 这样写后， Format的函数特性就被打破了
 * @param <T>
 */
public abstract class BaseFormat<T> implements Format<T>{
    protected String template;
    protected String replaceRegex;
    protected Pattern replacePattern;
    public BaseFormat() {
    }
    protected void initialization(String template,String regex){
        this.template = template;
        this.replaceRegex = regex;
        this.replacePattern = Pattern.compile(replaceRegex);
    }

    /**
     * 使用该方法时要慎重，注意模板的替换顺序
     * Be cautions when using this method
     * caution: order in witch the templates are replaced
     *
     * @param replaceStrings
     * @return
     */
    protected String replace(String... replaceStrings){
        Matcher matcher = replacePattern.matcher(template);
        StringBuffer sb = new StringBuffer();
        for (int i = 0;matcher.find() && i<replaceStrings.length;i++){
            matcher.appendReplacement(sb, replaceStrings[i]==null?
                    "":replaceStrings[i]);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
